from PIL import Image
import urllib.request
import glob
import os

def convert(imgname):
  img = Image.open(r'E:\python\captcha\%s.jpg' % imgname) # 读入图片
  # img = Image.open(r'E:\python\captcha\1.jpg').convert('1')
  img = img.convert("RGBA")

  pixdata = img.load()
  #二值化
  for y in range(img.size[1]):
    for x in range(img.size[0]):
      if pixdata[x, y][0] < 90:
        pixdata[x, y] = (0, 0, 0, 255)
      if pixdata[x, y][1] < 136:
        pixdata[x, y] = (0, 0, 0, 255)
      if pixdata[x, y][2] > 0:
        pixdata[x, y] = (255, 255, 255, 255)

  img.save(r'E:\python\captcha\new\%s.gif' % imgname)

def printpix(imgname):
  img = Image.open(r'E:\python\captcha\new\%s.gif' % imgname)
  for h in range(26):
    for w in range(78):
      print(img.getpixel((w, h)), end='')
    print('')

'''返回最左边开始的点阵坐标(11,22)'''
def lposition(img):
  cod = []
  for x, h in enumerate(range(26)):
    for y, w in enumerate(range(78)):
      result = img.getpixel((w, h))
      if result == 1:
        cod.append((x+1,y+1))
        break
  cod = sorted(list((w,h) for h,w in cod))
  return cod[0]

def rposition(img):
  cod = []
  for x, h in enumerate(range(26)):
    for y, w in enumerate(range(77, 0, -1)):
      result = img.getpixel((w, h))
      if result == 1:
        cod.append((x+1,y+1))
        break
  cod = sorted(list((w,h) for h,w in cod))
  return cod[0]

def crop(img):
  lp = lposition(img)[0]
  #这里的坐标34是中间位置,大部分验证码的中间位置在这个位置左右
  left = (lp, 0, 34, 26)
  region = img.crop(left)
  region.save(r'E:\python\captcha\new\region-1.gif')

  img.crop((lp, 0, (lp+int((34-lp)/2)), 26)).save(r'E:\python\captcha\new\region-10.gif')
  img.crop(((lp+int((34-lp)/2)), 0, 34, 26)).save(r'E:\python\captcha\new\region-11.gif')

  rp = rposition(img)[0]
  right = (35, 0, 78-rp, 26)
  img.crop((right)).save(r'E:\python\captcha\new\region-2.gif')
  img.crop((35, 0, 35+int((78-35-rp)/2), 26)).save(r'E:\python\captcha\new\region-20.gif')
  img.crop((35+int((78-35-rp)/2), 0, 78-rp, 26)).save(r'E:\python\captcha\new\region-21.gif')

class Captcha:
  def __init__(self):
    pass

  def download_img(self):
    for i in range(1, 100):  
      url = 'http://su.100steps.net/2007/vote/verify.php'
      print('download',i)
      with open(r'E:\python\captcha\%s.png' % i, 'wb') as f:
        f.write(urllib.request.urlopen(url).read())

  def get_sample(self):
    os.chdir(r'E:\python\captcha')
    for i in glob.glob('*.png'):
      img = Image.open(os.path.join(r'E:\python\captcha', i)).convert('1')
      for a,b in enumerate(range(5)):
        x,y = 10 + b * 18,6
        img.crop((x, y, x+8, y+10)).save(r'E:\python\captcha\new\%s-%s.bmp' % (os.path.splitext(i)[0],a))

  def recognize(self, img):
    sample = []
    os.chdir(r'E:\python\captcha\new')
    for i in glob.glob('*.bmp'):
      sample.append((os.path.splitext(i)[0], Image.open(os.path.join(r'E:\python\captcha\new', i))))

    result = ''
    for x in range(5):
      point = []
      x,y=10+x*18,6
      letter = img.crop((x, y, x+8, y+10))
      for text,s in sample:
        diffs = 0
        for yi in range(10):
          for xi in range(8):
            if s.getpixel((xi,yi)) != letter.getpixel((xi,yi)):
              diffs += 1
        point.append((diffs, text))
      point.sort()
      result += point[0][1]
    print(result)

if __name__ == '__main__':
  captcha = Captcha()
  img = Image.open(r'E:\python\captcha\10.png')
  captcha.recognize(img)